/**
 * @auth Noah Liu
 * @team 星城前端团队
 * 配合Uni的 PullDown 和 reachBottom 完成分页逻辑
 */

import { LooseObject } from "@/entity";
import { ref } from "vue";

enum LoadStatues {
  more = "more",
  noMore = "noMore",
  loading = "loading",
}

export const contentText = {
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多了",
};

export interface PaginationRes {
  content: LooseObject[];
  empty: boolean;
  first: boolean;
  last: boolean;
  number: number;
  numberOfElements: number;
  pageable: {
    offset: number;
    pageNumber: number;
    pageSize: number;
    paged: boolean;
  };
  size: number;
  sort: object;
  totalElements: number;
  totalPages: number;
}

export function usePagination() {
  /** 列表是否加载中 */
  let listLoading = ref(false);
  /** 列表加载状态 */
  let loadStatus = ref(LoadStatues.more);
  /** 当前页码 */
  let page = ref(1);
  /** 页面显示动作 */
  function handlerShow() {
    page.value = 1;
    uni.startPullDownRefresh({});
  }
  /**
   * 页面下拉事件动作
   * @param callback 数据加载方法
   */
  function pullDownRefresh(callback: (isPUll: boolean) => void) {
    page.value = 1;
    listLoading.value = true;
    callback(true);
  }
  /**
   * 页面上拉到底事件动作
   * @param callback 数据加载方法
   */
  function reachBottom(callback: (isPull: boolean) => void) {
    if (!listLoading.value && loadStatus.value !== LoadStatues.noMore) {
      page.value++;
      listLoading.value = true;
      loadStatus.value = LoadStatues.loading;
      callback(false);
    }
  }
  /**
   * 数据加载完成动作
   * @param hasMore 是否有更多数据
   */
  function afterGetList(hasMore?: boolean) {
    if (hasMore !== undefined) {
      loadStatus.value = hasMore ? LoadStatues.more : LoadStatues.noMore;
    }
    uni.stopPullDownRefresh();
    listLoading.value = false;
  }
  return {
    listLoading,
    loadStatus,
    page,
    handlerShow,
    pullDownRefresh,
    reachBottom,
    afterGetList,
  };
}
